// let webSocket = null;
// let socketOpen = false;
 
// // 发送消息
// export const doSend = (message) => {
//   if (socketOpen) {
//     webSocket.send(message)
//   }
// }
 
// // 初始化websocket
// export const contactSocket = (username) => {
//   if ("WebSocket" in window) {
//     var received_msg = ''
//     webSocket = new WebSocket("ws://192.168.99.117:3000?name=#username#".replace('#username#', username));
//     webSocket.onopen = function () {
//       console.log("连接成功！");
//       socketOpen = true
//       this.received_msg = "连接成功"
//     };
//     webSocket.onmessage = function (evt) {
//       received_msg = evt.data;
//       this.console.log("接受消息：" + received_msg);
//     };
//     webSocket.onclose = function () {
//       console.log("连接关闭！");
//       this.received_msg = "连接关闭"
//     };
//     webSocket.onerror = function () {
//       console.log("连接异常！");
//       this.received_msg = "连接异常"
//     };
//     return "sad";
//   }
// }

// websocket.js

class WebSocketUtil {
  constructor() {
    this.socket = null;
  }

  connect(url) {
    this.socket = new WebSocket(url);

    return new Promise((resolve, reject) => {
      this.socket.onopen = () => {
        resolve();
      };

      this.socket.onerror = (error) => {
        reject(error);
      };
    });
  }

  close() {
    if (this.socket) {
      this.socket.close();
    }
  }

  sendMessage(message) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
    }
  }

  receiveMessage(callback) {
    if (this.socket) {
      this.socket.onmessage = (event) => {
        callback(event.data);
      };
    }
  }
}

export default WebSocketUtil;
